package com.example.charlotte.snakegame;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends BaseActivity {
    private GameMusic music;
    private EditText editText1;
    private EditText editText2;
    private MyDB myDB;
    private SharedPreferences.Editor editor;
    private SharedPreferences saved;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        saved = PreferenceManager.getDefaultSharedPreferences(this);
        music=new GameMusic(this);

        editText1=findViewById(R.id.editText1);
        editText2=findViewById(R.id.editText2);

    }
    @Override
    protected void onStart() {
        super.onStart();
        myDB=new MyDB(this,"User.db");
        myDB.open();
    }
    protected void onStop() {
        super.onStop();
        if (myDB != null) {
            myDB.close();
        }
    }

    public void loginUser(View view) {
        music.startMusic(3);
        if (TextUtils.isEmpty(editText1.getText()) || TextUtils.isEmpty(editText2.getText())) {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        }else {
            String userName = editText1.getText().toString().trim();
            String passWord = editText2.getText().toString();
            String md5Psw = MD5Utils.md5(passWord);

            if (checkLogin(userName, md5Psw)) {
                editor = saved.edit();
                editor.putString("name", userName)
                .putString("pass", md5Psw)
                .putString("lastName", userName)
                .putBoolean("isLogin", true)
                .commit();
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();

            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //验证登录
    private boolean checkLogin(String username,String password) {
        Cursor cursor=myDB.queryByName(username,password);
        if (cursor.moveToFirst()){
            cursor.close();
            return true;
        }
        return false;
    }
    public void register(View view) {
        music.startMusic(3);
        startActivity(new Intent(this,RegisterActivity.class));

    }

}
